# -*- coding: utf-8 -*-
from program_top.utilities.csv_and_json_serialisation import buffered_dict
from program_top.utilities.decorators import as_main
from program_top.utilities.ip_and_socket import scan_available_ports_then_return
from program_top.components.zmq_io_interface import zmq_io_gateway
from program_top.components.tcp_io_gateway import tcp_gateway

class as_single_server(as_main):
	'''使target_class类的实例作为单例服务器运行，并从端口监听消息传入，不能在同一个main中构造多个被as_single_server装饰的实例'''
	def __init__(self,target_class):
		assert_string="请确保业务执行类%s的定义中有self.intry入口函数，否则它的实例将无法接收消息，目前实例构造失败"%target_class.__name__
		assert hasattr(target_class,"intry"), assert_string
		super(as_single_server, self).__init__(target_class)#调用父类构造函数
		pass
		
	def try_bind_port(self,port):
		
		pass
	
	def __initialise_port_map(self):
		'''初始化服务器端口字典'''
		server_buffer_path=self.environment_pack['class_path']['buffer_dir']
		server_buffer_filename=server_buffer_path+"server_port_map.json"
		self.server_port_map=buffered_dict(server_buffer_filename)#能缓存的字典
		
	def __call__(self, *args, **kwargs):
		#self.__initialise_port_map()
		#self.__apply_port_from_sys()
		self.working_instance=self.working_type(*args,**kwargs)
		self.io_gateway=tcp_gateway(self.listen_port,self.working_instance.intry)
		pass
	
	def __apply_port_from_sys(self):
		'''向系统申请端口'''
		if self.server_port_map.__contains__(self.working_type.__name__):
			using_port=self.server_port_map[self.working_type.__name__]
		else:
			using_port=scan_available_ports_then_return(
				self.environment_pack['current_platform_info']['current_system_category'])#向系统申请一个端口
			self.server_port_map[self.working_type.__name__]=using_port
		self.listen_port=using_port
	
	pass


